using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 尾部风险监控类 - 极端损失保护机制
    /// 识别和防范极端市场事件，建立多层次的风险防护机制
    /// </summary>
    public class TailRiskMonitor
    {
        #region 常量定义

        // 预警阈值
        public const double NORMAL_RISK_THRESHOLD = 0.02;       // 正常风险阈值2%
        public const double CAUTION_RISK_THRESHOLD = 0.05;      // 注意风险阈值5%
        public const double WARNING_RISK_THRESHOLD = 0.08;      // 警告风险阈值8%
        public const double CRITICAL_RISK_THRESHOLD = 0.12;     // 严重风险阈值12%

        // 尾部风险参数
        public const double EXTREME_VAR_MULTIPLIER = 2.0;       // 极端VaR倍数
        public const double TAIL_EVENT_THRESHOLD = 0.99;        // 尾部事件置信水平99%
        public const int TAIL_EVENT_LOOKBACK_DAYS = 30;         // 尾部事件回顾天数

        // 压力测试参数
        public const double STRESS_VOLATILITY_MULTIPLIER = 2.5;  // 压力测试波动率倍数
        public const double CRASH_SCENARIO_DROP = 0.20;         // 崩盘情形20%跌幅
        public const double FLASH_CRASH_DROP = 0.10;            // 闪崩情形10%跌幅

        // 熔断保护参数
        public const double CIRCUIT_BREAKER_THRESHOLD = 0.15;    // 熔断阈值15%
        public const int COOLING_OFF_MINUTES = 30;              // 冷却期30分钟

        #endregion

        #region 私有字段

        private readonly RiskMetrics _riskMetrics;
        private readonly List<RiskEvent> _riskEventHistory;
        private readonly List<double> _dailyReturns;
        private readonly List<TailRiskReport> _reportHistory;
        private DateTime _lastCircuitBreakerTime;
        private bool _isCircuitBreakerActive;
        private LeverageController.RiskLevel _currentRiskLevel;
        private DateTime _lastUpdateTime;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化尾部风险监控模块
        /// </summary>
        /// <param name="riskMetrics">风险度量模块</param>
        public TailRiskMonitor(RiskMetrics riskMetrics)
        {
            _riskMetrics = riskMetrics ?? throw new ArgumentNullException(nameof(riskMetrics));
            _riskEventHistory = new List<RiskEvent>();
            _dailyReturns = new List<double>();
            _reportHistory = new List<TailRiskReport>();
            _lastCircuitBreakerTime = DateTime.MinValue;
            _isCircuitBreakerActive = false;
            _currentRiskLevel = LeverageController.RiskLevel.Safe;
            _lastUpdateTime = DateTime.MinValue;
        }

        #endregion

        #region 核心风险监控方法

        /// <summary>
        /// 执行全面的尾部风险监控
        /// </summary>
        /// <param name="positionValue">当前仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <param name="currentPrice">当前价格</param>
        /// <returns>尾部风险监控报告</returns>
        public TailRiskReport MonitorTailRisk(double positionValue, double accountEquity, double currentPrice)
        {
            var report = new TailRiskReport
            {
                MonitoringTime = DateTime.Now,
                PositionValue = positionValue,
                AccountEquity = accountEquity,
                CurrentPrice = currentPrice
            };

            try
            {
                // 1. VaR突破频率检查
                report.VaRBreachAnalysis = AnalyzeVaRBreaches();

                // 2. 极端损失检测
                report.ExtremeLossDetection = DetectExtremeLoss(positionValue, accountEquity);

                // 3. 尾部风险评估
                report.TailRiskAssessment = AssessTailRisk(positionValue, accountEquity);

                // 4. 压力测试结果
                report.StressTestResults = RunStressTests(positionValue, accountEquity, currentPrice);

                // 5. 风险等级评估
                report.RiskLevel = EvaluateOverallRiskLevel(report);
                _currentRiskLevel = report.RiskLevel;

                // 6. 熔断检查
                report.CircuitBreakerStatus = CheckCircuitBreaker(report);

                // 7. 生成预警和建议
                report.Warnings = GenerateWarnings(report);
                report.Recommendations = GenerateRecommendations(report);

                report.IsValid = true;
                _lastUpdateTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                report.ErrorMessage = $"尾部风险监控异常: {ex.Message}";
                report.IsValid = false;
                report.RiskLevel = LeverageController.RiskLevel.Safe;
            }

            // 记录到历史
            _reportHistory.Add(report);
            
            // 保持历史记录在合理范围内
            if (_reportHistory.Count > 1000)
            {
                _reportHistory.RemoveRange(0, _reportHistory.Count - 1000);
            }

            return report;
        }

        /// <summary>
        /// 分析VaR突破情况
        /// </summary>
        /// <returns>VaR突破分析结果</returns>
        private VaRBreachAnalysis AnalyzeVaRBreaches()
        {
            var analysis = new VaRBreachAnalysis();

            if (!_riskMetrics.IsDataSufficient())
            {
                analysis.Message = "历史数据不足，无法分析VaR突破";
                return analysis;
            }

            try
            {
                // 模拟计算最近的VaR突破情况
                var recentReports = _reportHistory.Where(r => 
                    r.MonitoringTime > DateTime.Now.AddDays(-TAIL_EVENT_LOOKBACK_DAYS)).ToList();

                if (recentReports.Count < 10)
                {
                    analysis.Message = "历史报告数据不足";
                    return analysis;
                }

                // 计算突破频率
                int totalObservations = recentReports.Count;
                int breaches95 = recentReports.Count(r => 
                    r.TailRiskAssessment?.IsExtremeEvent == true);
                
                analysis.BreachFrequency95 = (double)breaches95 / totalObservations;
                analysis.ExpectedFrequency95 = 0.05; // 5% expected for 95% confidence
                analysis.IsBreachRateNormal = Math.Abs(analysis.BreachFrequency95 - analysis.ExpectedFrequency95) < 0.02;
                
                analysis.Message = analysis.IsBreachRateNormal ? 
                    "VaR模型有效性正常" : "VaR模型可能失效，需要重新校准";

                analysis.IsValid = true;
            }
            catch (Exception ex)
            {
                analysis.Message = $"VaR突破分析异常: {ex.Message}";
                analysis.IsValid = false;
            }

            return analysis;
        }

        /// <summary>
        /// 检测极端损失事件
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>极端损失检测结果</returns>
        private ExtremeLossDetection DetectExtremeLoss(double positionValue, double accountEquity)
        {
            var detection = new ExtremeLossDetection();

            if (!_riskMetrics.IsDataSufficient())
            {
                detection.Message = "数据不足，无法检测极端损失";
                return detection;
            }

            try
            {
                // 计算99%置信水平的VaR和CVaR
                double var99 = _riskMetrics.CalculateHistoricalVaR(
                    RiskMetrics.CONFIDENCE_LEVEL_99, positionValue);
                double cvar99 = _riskMetrics.CalculateCVaR(
                    RiskMetrics.CONFIDENCE_LEVEL_99, positionValue);

                // 计算风险度量比率
                detection.VaR99Ratio = var99 / accountEquity;
                detection.CVaR99Ratio = cvar99 / accountEquity;

                // 计算极端VaR（使用倍数增强）
                detection.ExtremeVaR = var99 * EXTREME_VAR_MULTIPLIER;
                detection.ExtremeVaRRatio = detection.ExtremeVaR / accountEquity;

                // 判断是否为极端事件
                detection.IsExtremeVaR = detection.VaR99Ratio > WARNING_RISK_THRESHOLD;
                detection.IsExtremeCVaR = detection.CVaR99Ratio > CRITICAL_RISK_THRESHOLD;
                detection.IsExtremeEvent = detection.IsExtremeVaR || detection.IsExtremeCVaR;

                // 风险等级评估
                if (detection.ExtremeVaRRatio > CRITICAL_RISK_THRESHOLD)
                {
                    detection.RiskLevel = "严重";
                }
                else if (detection.ExtremeVaRRatio > WARNING_RISK_THRESHOLD)
                {
                    detection.RiskLevel = "警告";
                }
                else if (detection.ExtremeVaRRatio > CAUTION_RISK_THRESHOLD)
                {
                    detection.RiskLevel = "注意";
                }
                else
                {
                    detection.RiskLevel = "正常";
                }

                detection.Message = $"VaR99: {detection.VaR99Ratio:P2}, CVaR99: {detection.CVaR99Ratio:P2}, " +
                                  $"极端VaR: {detection.ExtremeVaRRatio:P2}";
                detection.IsValid = true;
            }
            catch (Exception ex)
            {
                detection.Message = $"极端损失检测异常: {ex.Message}";
                detection.IsValid = false;
            }

            return detection;
        }

        /// <summary>
        /// 评估尾部风险
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>尾部风险评估结果</returns>
        private TailRiskAssessment AssessTailRisk(double positionValue, double accountEquity)
        {
            var assessment = new TailRiskAssessment();

            if (!_riskMetrics.IsDataSufficient())
            {
                assessment.Message = "数据不足，无法评估尾部风险";
                return assessment;
            }

            try
            {
                // 获取风险度量数据
                var (priceCount, returnCount, volatility, lastUpdate) = _riskMetrics.GetDataStatus();
                
                // 计算尾部风险指标
                assessment.CurrentVolatility = volatility;
                assessment.VolatilityRank = CalculateVolatilityRank(volatility);
                
                // 尾部概率估计
                assessment.TailProbability = EstimateTailProbability(positionValue, accountEquity);
                
                // 极端事件风险评估
                assessment.IsExtremeEvent = assessment.TailProbability > 0.01; // 1%尾部概率
                assessment.ExtremeEventRisk = assessment.TailProbability * 100; // 转换为百分比

                // 尾部期望损失
                assessment.ExpectedTailLoss = CalculateExpectedTailLoss(positionValue, accountEquity);
                assessment.TailLossRatio = assessment.ExpectedTailLoss / accountEquity;

                // 风险评级
                if (assessment.TailLossRatio > 0.15)
                {
                    assessment.TailRiskRating = "极高";
                }
                else if (assessment.TailLossRatio > 0.10)
                {
                    assessment.TailRiskRating = "高";
                }
                else if (assessment.TailLossRatio > 0.05)
                {
                    assessment.TailRiskRating = "中";
                }
                else
                {
                    assessment.TailRiskRating = "低";
                }

                assessment.Message = $"尾部风险评级: {assessment.TailRiskRating}, " +
                                   $"预期尾部损失比率: {assessment.TailLossRatio:P2}";
                assessment.IsValid = true;
            }
            catch (Exception ex)
            {
                assessment.Message = $"尾部风险评估异常: {ex.Message}";
                assessment.IsValid = false;
            }

            return assessment;
        }

        /// <summary>
        /// 执行压力测试
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <param name="currentPrice">当前价格</param>
        /// <returns>压力测试结果</returns>
        private StressTestResults RunStressTests(double positionValue, double accountEquity, double currentPrice)
        {
            var results = new StressTestResults();

            try
            {
                // 场景1：市场崩盘（20%下跌）
                double crashLoss = positionValue * CRASH_SCENARIO_DROP;
                results.CrashScenarioLoss = crashLoss;
                results.CrashScenarioImpact = crashLoss / accountEquity;

                // 场景2：闪崩事件（10%快速下跌）
                double flashCrashLoss = positionValue * FLASH_CRASH_DROP;
                results.FlashCrashLoss = flashCrashLoss;
                results.FlashCrashImpact = flashCrashLoss / accountEquity;

                // 场景3：波动率飙升
                if (_riskMetrics.IsDataSufficient())
                {
                    double normalVolatility = _riskMetrics.CalculateVolatility();
                    double stressVolatility = normalVolatility * STRESS_VOLATILITY_MULTIPLIER;
                    
                    // 模拟高波动环境下的VaR
                    double stressVaR = positionValue * stressVolatility * RiskMetrics.Z_SCORE_95 / Math.Sqrt(250);
                    results.HighVolatilityVaR = stressVaR;
                    results.HighVolatilityImpact = stressVaR / accountEquity;
                }

                // 综合压力测试评级
                double maxImpact = Math.Max(results.CrashScenarioImpact, 
                                   Math.Max(results.FlashCrashImpact, results.HighVolatilityImpact));

                if (maxImpact > 0.20)
                {
                    results.StressTestRating = "不通过";
                    results.StressTestPassed = false;
                }
                else if (maxImpact > 0.10)
                {
                    results.StressTestRating = "勉强通过";
                    results.StressTestPassed = true;
                }
                else
                {
                    results.StressTestRating = "通过";
                    results.StressTestPassed = true;
                }

                results.Message = $"最大损失影响: {maxImpact:P2}, 评级: {results.StressTestRating}";
                results.IsValid = true;
            }
            catch (Exception ex)
            {
                results.Message = $"压力测试异常: {ex.Message}";
                results.IsValid = false;
                results.StressTestPassed = false;
            }

            return results;
        }

        /// <summary>
        /// 检查熔断机制
        /// </summary>
        /// <param name="report">风险监控报告</param>
        /// <returns>熔断状态</returns>
        private CircuitBreakerStatus CheckCircuitBreaker(TailRiskReport report)
        {
            var status = new CircuitBreakerStatus();

            try
            {
                // 检查冷却期
                bool inCoolingPeriod = (DateTime.Now - _lastCircuitBreakerTime).TotalMinutes < COOLING_OFF_MINUTES;
                
                // 检查熔断触发条件
                bool shouldTrigger = false;
                var reasons = new List<string>();

                // 条件1：极端损失超过阈值
                if (report.ExtremeLossDetection?.ExtremeVaRRatio > CIRCUIT_BREAKER_THRESHOLD)
                {
                    shouldTrigger = true;
                    reasons.Add($"极端VaR比率{report.ExtremeLossDetection.ExtremeVaRRatio:P2}超过熔断阈值{CIRCUIT_BREAKER_THRESHOLD:P2}");
                }

                // 条件2：压力测试严重失败
                if (report.StressTestResults?.StressTestPassed == false && 
                    Math.Max(report.StressTestResults.CrashScenarioImpact, report.StressTestResults.FlashCrashImpact) > CIRCUIT_BREAKER_THRESHOLD)
                {
                    shouldTrigger = true;
                    reasons.Add("压力测试显示潜在损失超过熔断阈值");
                }

                // 条件3：风险等级达到严重级别
                if (report.RiskLevel == LeverageController.RiskLevel.Critical)
                {
                    shouldTrigger = true;
                    reasons.Add("整体风险等级达到严重级别");
                }

                // 更新熔断状态
                if (shouldTrigger && !inCoolingPeriod)
                {
                    _isCircuitBreakerActive = true;
                    _lastCircuitBreakerTime = DateTime.Now;
                    status.IsActive = true;
                    status.TriggeredTime = DateTime.Now;
                    status.Reasons = reasons;
                    status.Message = $"熔断机制触发: {string.Join("; ", reasons)}";
                }
                else if (inCoolingPeriod)
                {
                    status.IsActive = true;
                    status.TriggeredTime = _lastCircuitBreakerTime;
                    status.RemainingCoolingMinutes = COOLING_OFF_MINUTES - (int)(DateTime.Now - _lastCircuitBreakerTime).TotalMinutes;
                    status.Message = $"熔断冷却期，剩余{status.RemainingCoolingMinutes}分钟";
                }
                else
                {
                    _isCircuitBreakerActive = false;
                    status.IsActive = false;
                    status.Message = "熔断机制正常";
                }

                status.IsValid = true;
            }
            catch (Exception ex)
            {
                status.Message = $"熔断检查异常: {ex.Message}";
                status.IsValid = false;
            }

            return status;
        }

        #endregion

        #region 辅助计算方法

        /// <summary>
        /// 计算波动率排名
        /// </summary>
        /// <param name="currentVolatility">当前波动率</param>
        /// <returns>波动率排名（0-100）</returns>
        private double CalculateVolatilityRank(double currentVolatility)
        {
            // 简化的波动率排名计算
            if (currentVolatility <= 0.10) return 10; // 低波动
            if (currentVolatility <= 0.20) return 40; // 中等波动
            if (currentVolatility <= 0.30) return 70; // 较高波动
            return 95; // 高波动
        }

        /// <summary>
        /// 估计尾部概率
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>尾部概率</returns>
        private double EstimateTailProbability(double positionValue, double accountEquity)
        {
            if (!_riskMetrics.IsDataSufficient())
            {
                return 0.01; // 默认1%尾部概率
            }

            try
            {
                // 基于当前波动率估计尾部概率
                double volatility = _riskMetrics.CalculateVolatility();
                double riskRatio = positionValue / accountEquity;
                
                // 简化的尾部概率模型
                double baseProbability = 0.005; // 基础0.5%概率
                double volatilityAdjustment = Math.Min(volatility / 0.20, 2.0); // 波动率调整
                double positionAdjustment = Math.Min(riskRatio, 2.0); // 仓位调整
                
                return baseProbability * volatilityAdjustment * positionAdjustment;
            }
            catch
            {
                return 0.01;
            }
        }

        /// <summary>
        /// 计算预期尾部损失
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>预期尾部损失</returns>
        private double CalculateExpectedTailLoss(double positionValue, double accountEquity)
        {
            if (!_riskMetrics.IsDataSufficient())
            {
                // 使用保守估计
                return positionValue * 0.10; // 假设10%的尾部损失
            }

            try
            {
                // 使用CVaR作为预期尾部损失的估计
                return _riskMetrics.CalculateCVaR(RiskMetrics.CONFIDENCE_LEVEL_95, positionValue);
            }
            catch
            {
                return positionValue * 0.10;
            }
        }

        /// <summary>
        /// 评估整体风险等级
        /// </summary>
        /// <param name="report">风险报告</param>
        /// <returns>风险等级</returns>
        private LeverageController.RiskLevel EvaluateOverallRiskLevel(TailRiskReport report)
        {
            // 收集各项风险指标
            var riskFactors = new List<double>();

            if (report.ExtremeLossDetection?.IsValid == true)
            {
                riskFactors.Add(report.ExtremeLossDetection.ExtremeVaRRatio);
            }

            if (report.TailRiskAssessment?.IsValid == true)
            {
                riskFactors.Add(report.TailRiskAssessment.TailLossRatio);
            }

            if (report.StressTestResults?.IsValid == true)
            {
                double maxStressImpact = Math.Max(report.StressTestResults.CrashScenarioImpact,
                                                report.StressTestResults.FlashCrashImpact);
                riskFactors.Add(maxStressImpact);
            }

            if (riskFactors.Count == 0)
            {
                return LeverageController.RiskLevel.Safe;
            }

            // 取最大风险指标作为整体评估基础
            double maxRisk = riskFactors.Max();

            if (maxRisk >= CRITICAL_RISK_THRESHOLD)
                return LeverageController.RiskLevel.Critical;
            else if (maxRisk >= WARNING_RISK_THRESHOLD)
                return LeverageController.RiskLevel.High;
            else if (maxRisk >= CAUTION_RISK_THRESHOLD)
                return LeverageController.RiskLevel.Moderate;
            else
                return LeverageController.RiskLevel.Low;
        }

        /// <summary>
        /// 生成风险预警
        /// </summary>
        /// <param name="report">风险报告</param>
        /// <returns>预警列表</returns>
        private List<string> GenerateWarnings(TailRiskReport report)
        {
            var warnings = new List<string>();

            // VaR突破预警
            if (report.VaRBreachAnalysis?.IsBreachRateNormal == false)
            {
                warnings.Add("VaR模型可能失效，建议重新校准");
            }

            // 极端损失预警
            if (report.ExtremeLossDetection?.IsExtremeEvent == true)
            {
                warnings.Add($"检测到极端损失风险，VaR99比率达到{report.ExtremeLossDetection.VaR99Ratio:P2}");
            }

            // 尾部风险预警
            if (report.TailRiskAssessment?.TailRiskRating == "高" || report.TailRiskAssessment?.TailRiskRating == "极高")
            {
                warnings.Add($"尾部风险等级: {report.TailRiskAssessment.TailRiskRating}，预期损失比率{report.TailRiskAssessment.TailLossRatio:P2}");
            }

            // 压力测试预警
            if (report.StressTestResults?.StressTestPassed == false)
            {
                warnings.Add($"压力测试未通过，评级: {report.StressTestResults.StressTestRating}");
            }

            // 熔断预警
            if (report.CircuitBreakerStatus?.IsActive == true)
            {
                warnings.Add($"熔断机制已激活: {report.CircuitBreakerStatus.Message}");
            }

            return warnings;
        }

        /// <summary>
        /// 生成风险管理建议
        /// </summary>
        /// <param name="report">风险报告</param>
        /// <returns>建议列表</returns>
        private List<string> GenerateRecommendations(TailRiskReport report)
        {
            var recommendations = new List<string>();

            switch (report.RiskLevel)
            {
                case LeverageController.RiskLevel.Critical:
                    recommendations.Add("建议立即减仓至最小风险水平");
                    recommendations.Add("暂停新开仓，等待市场稳定");
                    recommendations.Add("增加止损保护，降低单笔损失上限");
                    break;

                case LeverageController.RiskLevel.High:
                    recommendations.Add("建议适当减小仓位规模");
                    recommendations.Add("加强风险监控频率");
                    recommendations.Add("考虑设置更严格的止损条件");
                    break;

                case LeverageController.RiskLevel.Moderate:
                    recommendations.Add("保持当前仓位水平");
                    recommendations.Add("密切关注市场波动变化");
                    recommendations.Add("准备风险应对预案");
                    break;

                case LeverageController.RiskLevel.Low:
                case LeverageController.RiskLevel.Safe:
                    recommendations.Add("风险水平正常，可维持当前策略");
                    recommendations.Add("继续定期风险评估");
                    break;

                default:
                    recommendations.Add("数据不足，建议谨慎操作");
                    break;
            }

            return recommendations;
        }

        #endregion

        #region 公共接口方法

        /// <summary>
        /// 获取当前风险等级
        /// </summary>
        /// <returns>当前风险等级</returns>
        public LeverageController.RiskLevel GetCurrentRiskLevel()
        {
            return _currentRiskLevel;
        }

        /// <summary>
        /// 检查是否处于熔断状态
        /// </summary>
        /// <returns>熔断状态</returns>
        public bool IsCircuitBreakerActive()
        {
            return _isCircuitBreakerActive && 
                   (DateTime.Now - _lastCircuitBreakerTime).TotalMinutes < COOLING_OFF_MINUTES;
        }

        /// <summary>
        /// 获取最近的风险报告
        /// </summary>
        /// <param name="count">报告数量</param>
        /// <returns>风险报告列表</returns>
        public List<TailRiskReport> GetRecentReports(int count = 10)
        {
            return _reportHistory.TakeLast(count).ToList();
        }

        /// <summary>
        /// 清除历史数据
        /// </summary>
        public void ClearHistory()
        {
            _reportHistory.Clear();
            _riskEventHistory.Clear();
            _dailyReturns.Clear();
        }

        /// <summary>
        /// 获取监控状态
        /// </summary>
        /// <returns>监控状态信息</returns>
        public (LeverageController.RiskLevel CurrentLevel, bool CircuitBreakerActive, DateTime LastUpdate, int ReportCount) GetMonitorStatus()
        {
            return (_currentRiskLevel, IsCircuitBreakerActive(), _lastUpdateTime, _reportHistory.Count);
        }

        #endregion
    }

    #region 尾部风险相关数据结构

    /// <summary>
    /// 尾部风险等级枚举
    /// </summary>
    public enum TailRiskLevel
    {
        Unknown,    // 未知
        Normal,     // 正常
        Caution,    // 注意
        Warning,    // 警告  
        Critical    // 严重
    }

    /// <summary>
    /// 风险事件记录
    /// </summary>
    public class RiskEvent
    {
        public DateTime EventTime { get; set; }
        public string EventType { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public double ImpactRatio { get; set; }
        public TailRiskLevel SeverityLevel { get; set; }
    }

    /// <summary>
    /// VaR突破分析结果
    /// </summary>
    public class VaRBreachAnalysis
    {
        public double BreachFrequency95 { get; set; }
        public double ExpectedFrequency95 { get; set; }
        public bool IsBreachRateNormal { get; set; }
        public string Message { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    /// <summary>
    /// 极端损失检测结果
    /// </summary>
    public class ExtremeLossDetection
    {
        public double VaR99Ratio { get; set; }
        public double CVaR99Ratio { get; set; }
        public double ExtremeVaR { get; set; }
        public double ExtremeVaRRatio { get; set; }
        public bool IsExtremeVaR { get; set; }
        public bool IsExtremeCVaR { get; set; }
        public bool IsExtremeEvent { get; set; }
        public string RiskLevel { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    /// <summary>
    /// 尾部风险评估结果
    /// </summary>
    public class TailRiskAssessment
    {
        public double CurrentVolatility { get; set; }
        public double VolatilityRank { get; set; }
        public double TailProbability { get; set; }
        public bool IsExtremeEvent { get; set; }
        public double ExtremeEventRisk { get; set; }
        public double ExpectedTailLoss { get; set; }
        public double TailLossRatio { get; set; }
        public string TailRiskRating { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    /// <summary>
    /// 压力测试结果
    /// </summary>
    public class StressTestResults
    {
        public double CrashScenarioLoss { get; set; }
        public double CrashScenarioImpact { get; set; }
        public double FlashCrashLoss { get; set; }
        public double FlashCrashImpact { get; set; }
        public double HighVolatilityVaR { get; set; }
        public double HighVolatilityImpact { get; set; }
        public string StressTestRating { get; set; } = string.Empty;
        public bool StressTestPassed { get; set; }
        public string Message { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    /// <summary>
    /// 熔断机制状态
    /// </summary>
    public class CircuitBreakerStatus
    {
        public bool IsActive { get; set; }
        public DateTime TriggeredTime { get; set; }
        public List<string> Reasons { get; set; } = new List<string>();
        public int RemainingCoolingMinutes { get; set; }
        public string Message { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    /// <summary>
    /// 尾部风险监控报告
    /// </summary>
    public class TailRiskReport
    {
        public DateTime MonitoringTime { get; set; }
        public double PositionValue { get; set; }
        public double AccountEquity { get; set; }
        public double CurrentPrice { get; set; }
        public VaRBreachAnalysis? VaRBreachAnalysis { get; set; }
        public ExtremeLossDetection? ExtremeLossDetection { get; set; }
        public TailRiskAssessment? TailRiskAssessment { get; set; }
        public StressTestResults? StressTestResults { get; set; }
        public CircuitBreakerStatus? CircuitBreakerStatus { get; set; }
        public LeverageController.RiskLevel RiskLevel { get; set; }
        public List<string> Warnings { get; set; } = new List<string>();
        public List<string> Recommendations { get; set; } = new List<string>();
        public string ErrorMessage { get; set; } = string.Empty;
        public bool IsValid { get; set; }
    }

    #endregion
}
